package com.zhongli.devplatform.service.impl.im;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhongli.devplatform.bean.PageVO;
import com.zhongli.devplatform.bean.Res;
import com.zhongli.devplatform.dto.im.IMUserInitDTO;
import com.zhongli.devplatform.mapper.im.ImUserMapper;
import com.zhongli.devplatform.po.im.ImUserPO;
import com.zhongli.devplatform.service.imp.im.IMRestAPIService;
import com.zhongli.devplatform.utils.BeanCopierUtil;
import com.zhongli.devplatform.utils.im.TencentIMRestAPIUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * 腾讯云 IM RestAPI 转发
 * @author WuXiCheng
 * @version 1.0
 */
@Slf4j
@Service
@Transactional
public class IMRestAPIServiceImpl implements IMRestAPIService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ImUserMapper imUserMapper;

    @Override
    public Res<JSONObject> dispatcher(String serviceName, JSONObject jobj) {

        if(!TencentIMRestAPIUtil.checkServiceName(serviceName)){
            return new Res<>(404, "未找到对应的服务: " + serviceName);
        }

        String serviceFullUrl = null;
        try {
            serviceFullUrl = TencentIMRestAPIUtil.getServiceFullUrl(serviceName);
        } catch (Exception e) {
            return new Res<>(500, e.getMessage());
        }

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<JSONObject> entity = new HttpEntity<>(jobj, headers);

        System.out.println(serviceFullUrl);
        System.out.println(jobj);

        ResponseEntity<JSONObject> responseEntity = restTemplate.exchange(serviceFullUrl, HttpMethod.POST, entity, JSONObject.class);

        // IM RestAPI 调用后执行
        CustomDoMain(serviceName, jobj, responseEntity.getBody());

        return Res.ok(responseEntity.getBody());
    }

    /**
     * 根据名称模糊查询用户
     * @param nick
     * @return
     */
    @Override
    public Res findByNick(String nick) {
        QueryWrapper<ImUserPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("nick",nick);
        IPage<ImUserPO> page = imUserMapper.selectPage(new Page<>(), queryWrapper);
        PageVO newPage = PageVO.convert(page);
        List<ImUserPO> imUserPOS = BeanCopierUtil.copy(page.getRecords(), ImUserPO.class);
        //List<ImUserPO> imUserPOList = BeanCopierUtil.copy(imUserPOS, ImUserPO.class);
        newPage.setRecords(imUserPOS);
        return Res.ok(newPage);
    }

    /**
     * 自定义服务调用前逻辑
     * @param serviceName
     * @param jobj
     */
    @Async
    protected void CustomDoMain(String serviceName, JSONObject jobj, JSONObject result){

        Integer errorCode = result.getInteger("ErrorCode");
        if(errorCode != 0){
            // RestAPI 出现错误时，不执行自定义的逻辑
//            return;
        }

        serviceName = serviceName.toLowerCase();

        if ("account_import".equals(serviceName)) {// 导入账号
            accountImport(jobj);
        }
    }

    @Override
    public void initIMUser(IMUserInitDTO dto){

        // ----------------- 导入账号 -----------------------

        JSONObject importAccountData = new JSONObject();

        importAccountData.put("Identifier", dto.getImId());
        importAccountData.put("Nick", dto.getNickName());
        importAccountData.put("FaceUrl", dto.getHeadImgUrl());

        Res<JSONObject> account_import_res = this.dispatcher("ACCOUNT_IMPORT", importAccountData);

        Integer errorCode = account_import_res.getData().getInteger("ErrorCode");

        log.info("IM_ACCOUNT_IMPORT", errorCode == 0 ? "成功" : ("失败:\t" + errorCode));

        if(errorCode != 0) return;

        log.info("initIMUser", "完成");
    }

    /**
     * 导入账号
     * @param jobj
     */
    private void accountImport(JSONObject jobj){
        // 导入账号时，添加数据
        ImUserPO imUser = jobj.toJavaObject(ImUserPO.class);
        if (imUser.getIdentifier()!=null){
            imUser.setImId(imUser.getIdentifier());
        }
        imUserMapper.insert(imUser);
    }

}
